package com.xxx.exception;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.xxx.common.dto.JsonResult;

@ControllerAdvice
public class GlobalExceptionResolver {

	private Logger logger = LogManager.getLogger(getClass());
	
	@ExceptionHandler(value = Exception.class)
	public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response,
			Exception exception) {
		StackTraceElement[] stackTrace = exception.getStackTrace();
		logger.error(exception.toString());
		logger.error(stackTrace[0]);
		String requestType = request.getHeader("X-Requested-With");
		if (StringUtils.isBlank(requestType)) {
			return new ModelAndView("/error/500");
		} else {
			JsonResult result = JsonResult.build(-1, "系统异常，请稍后重试！");
			String jsonString = JSON.toJSONString(result);
			response.setCharacterEncoding("UTF-8");
			response.setContentType("application/json; charset=utf-8");
			try {
				response.getWriter().write(jsonString);
				response.getWriter().flush();
				return null;
			} catch (IOException e) {

			}
		}
		return null;
	}
	
}
